package com.cheer.controller;

import com.cheer.common.Result;
import com.cheer.dto.MallAddressAddDTO;
import com.cheer.dto.MallAddressUpdateDTO;
import com.cheer.service.AuthService;
import com.cheer.service.MallAddressService;
import com.cheer.vo.MallAddressInfoVO;
import com.cheer.vo.MallAddressListVO;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.List;

/**
 * @author cheer
 */
@RestController
@RequestMapping("/address")
public class MallAddressController {

    @Autowired
    private MallAddressService mallAddressService;

    @Autowired
    private AuthService authService;

    @ApiOperation("查看用户收货地址列表")
    @GetMapping("/list")
    public Result<List<MallAddressListVO>> list(HttpSession session) {
        return Result.success(mallAddressService.listByUserId(authService.getUserId(session)));
    }

    @ApiOperation("添加收货地址")
    @PostMapping("/add")
    public Result add(@RequestBody @Valid MallAddressAddDTO addressAddDTO, HttpSession session) {
        mallAddressService.add(addressAddDTO, authService.getUserId(session));
        return Result.success();
    }

    @ApiOperation("查看收货地址详情")
    @GetMapping("/info")
    public Result<MallAddressInfoVO> info(@RequestParam Long id,
                                          HttpSession session) {
        authService.getUserId(session);
        return Result.success(mallAddressService.info(id));
    }

    @ApiOperation("修改收货地址")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid MallAddressUpdateDTO addressUpdateDTO, HttpSession session) {
        mallAddressService.update(addressUpdateDTO, authService.getUserId(session));
        return Result.success();
    }

    @ApiOperation("删除收货地址")
    @PostMapping("/delete")
    public Result delete(@RequestBody List<Long> ids,
                         HttpSession session) {
        authService.getUserId(session);
        if (CollectionUtils.isNotEmpty(ids)) {
            mallAddressService.removeByIds(ids);
        }
        return Result.success();
    }

    @ApiOperation("查询默认地址")
    @GetMapping("/default")
    public Result<MallAddressListVO> getDefault(HttpSession session) {
        return Result.success(mallAddressService.getDefault(authService.getUserId(session)));
    }
}
